package com.ryan.banner.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ryan.banner.entity.Banner;
import com.ryan.banner.service.BannerService;
import com.ryan.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

/**
 * <p>
 * 首页banner表 前端控制器
 * </p>
 *
 * @author ryan
 * @since 2020-07-28
 */
@RestController
@RequestMapping("/banner")
public class BannerController {

    @Autowired
    private BannerService bannerService;

    /**
     * 分页+条件查询所有banner
     * @param pageIndex
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/getAllBanner/{pageIndex}/{pageSize}")
    public R getAllAdvisor(@PathVariable long pageIndex,
                           @PathVariable long pageSize,
                           @RequestParam(required = false) String name){
        Page<Banner> resultPage = bannerService.queryPage(pageIndex, pageSize, name);
        return R.ok().data("list", resultPage.getRecords()).data("totalPage", resultPage.getTotal());
    }

    /**
     * 添加banner
     * @param banner
     * @return
     */
    @PostMapping("/addBanner")
    public R addBanner(@RequestBody Banner banner){
        boolean save = bannerService.save(banner);
        return save?R.ok():R.error();
    }

    /**
     * 更新banner
     * @param banner
     * @return
     */
    @PostMapping("/updateBanner")
    public R updateBanner(@RequestBody Banner banner){
        boolean update = bannerService.updateById(banner);
        return update?R.ok():R.error();
    }

    /**
     * 删除banner
     * @param ids
     * @return
     */
    @PostMapping("/deleteBanner")
    public R deleteBanner(@RequestBody Long[] ids){
        boolean delete = bannerService.removeByIds(Arrays.asList(ids));
        return delete?R.ok():R.error();
    }

    /**
     * 通过轮播图名称获取信息，主要作数据校验
     * @param title
     * @return
     */
    @GetMapping("/getBannerByTitle")
    public int getBannerByTitle(@RequestParam String title){
        QueryWrapper<Banner> wrapper = new QueryWrapper<>();
        wrapper.eq("title", title);
        int count = bannerService.count(wrapper);
        return count;
    }

    @GetMapping("/getBannerById/{id}")
    public R getBannerById(@PathVariable String id){
        Banner banner = bannerService.getById(id);
        return R.ok().data("banner", banner);
    }

}

